package com.bootx.predict;

import com.bootx.predict.pojo.PredictPlugin;
import com.bootx.predict.pojo.PredictionResult;
import com.bootx.predict.pojo.RedPacketBatch;
import com.bootx.predict.pojo.RedPacketRecord;
import com.bootx.predict.util.PredictUtils;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

@Component("bayesianPredict")
public class BayesianPredict extends PredictPlugin {

    private final double alphaPrior = 1;
    private final double betaPrior = 1;

    @Override
    public String getName() {
        return "bayesianPredict";
    }

    @Override
    public List<PredictionResult> predict(List<RedPacketBatch> list, Set<Integer> indexes) {
        List<RedPacketRecord> history = PredictUtils.parseData(list);
        // 按 index 分组
        Map<Integer, List<RedPacketRecord>> grouped = history.stream()
                .collect(Collectors.groupingBy(RedPacketRecord::getIndex));

        List<PredictionResult> results = new ArrayList<>();
        for (int idx : indexes) {
            List<RedPacketRecord> records = grouped.getOrDefault(idx, Collections.emptyList());
            int total = records.size();
            int oddCount = (int) records.stream().filter(r -> PredictUtils.isAmountOdd(r.getAmount())).count();
            int evenCount = total - oddCount;

            // 贝叶斯更新
            double alphaPost = alphaPrior + oddCount;
            double betaPost = betaPrior + evenCount;
            double probability = alphaPost / (alphaPost + betaPost);

            double avgOpenTime = records.stream().mapToInt(RedPacketRecord::getOpenTime).average().orElse(0);

            results.add(new PredictionResult(idx, total, oddCount, probability, Double.valueOf(avgOpenTime+"").intValue()));
        }
        return results;
    }
}
